package jevent;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Jose Carlos Palma
 * @version 1.1.0
 */
public class Main {

    public static void ayuda() {
        System.out.println("$ java -jar JEvent.jar port serverName serverIP serverPort");
        System.out.println("\tport      : Es el numero de puerto donde obtiene los triggers");
        System.out.println("\t            de la plataforma de prepago.");
        System.out.println("\tserverName: Es el nombre del servidor, es para llevar un control.");
        System.out.println("\t            Por ejemplo: AS400, HNG, etc.");
        System.out.println("\tserverIP  : Es la ip o host del servidor.");
        System.out.println("\t            Por ejemplo: 192.168.0.1 o as400.celtel.net");
        System.out.println("\tserverPort: Es el numero de puerto por donde escucha el servidor.");
        System.out.println("");
        System.out.println("$ java -jar JEvent.jar 6001 AS400 192.168.0.100 50000");
    }

    public static void main(String[] args) throws InterruptedException {


        ServerSocket server = null;
        Socket comverse = null;
        Socket cliente = null;
        PrintWriter pwCliente = null;
        BufferedReader br = null;

        if (args.length != 4) {
            System.out.println("Erorr: Parametros invalidos...\n");
            ayuda();
            System.exit(1);
        }
        if (!args[0].matches("[0-9]+")) {
            System.out.println("Erorr: Numero de puerto \"" + args[0] + "\" es invalido...\n");
            ayuda();
            System.exit(1);
        }
        if (!args[3].matches("[0-9]+")) {
            System.out.println("Erorr: Numero de puerto del servidor \"" + args[3] + "\" es invalido...\n");
            ayuda();
            System.exit(1);
        }
        int port = Integer.parseInt(args[0]);
        String serverName = args[1];
        String serverIP = args[2];
        int serverPort = Integer.parseInt(args[3]);

        ////////////////////////////////////////////////////////////////////////


        File f = new File(serverName + ".log");
        PrintWriter pwf = null;

        try {
            pwf = new PrintWriter(f);
        } catch (FileNotFoundException e) {
            println(pwf, "Error: No puedo crear el log[" + e.getMessage() + "]");
            System.exit(1);
        }

        ////////////////////////////////////////////////////////////////////////

        println(pwf, "Iniciando servicio...");
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            println(pwf, "Error: Al iniciar servicio[" + e.getMessage() + "]");
            System.exit(1);
        }
        println(pwf, "OK!");

        ////////////////////////////////////////////////////////////////////////

        println(pwf, "Esperando conexion con COMVERSE(Prepago)...");
        try {
            comverse = server.accept();
            br = new BufferedReader(new InputStreamReader(comverse.getInputStream()));
        } catch (IOException e) {
            println(pwf, "Error: Al conectarse con COMVERSE[" + e.getMessage() + "]");
            System.exit(1);
        }
        println(pwf, "OK!");


        ////////////////////////////////////////////////////////////////////////

        println(pwf, "Esperando conexion con " + serverName + "...");
        while (true) {

            try {
                cliente = new Socket(serverIP, serverPort);
            } catch (IOException e) {
                Thread.sleep(10000);
                System.out.print(".");
            }
            if (cliente != null) break;
        }
        println(pwf, "OK!");

        ////////////////////////////////////////////////////////////////////////

        println(pwf, "Obteniendo canal de envio al " + serverName);
        try{
            pwCliente = new PrintWriter(cliente.getOutputStream());

        }catch(IOException e){
            println(pwf, "Error: Al obtener canal de envio[" + e.getMessage() + "]");
            System.exit(1);
        }
        println(pwf, "OK!");

        ////////////////////////////////////////////////////////////////////////

        println(pwf, "lectura y envio de trama:");

        try
        {
            StringBuffer sb = null;
            Character cTmp = null;
            do
            {
                sb = new StringBuffer();
                if(cTmp != null)
                {
                    sb.append(cTmp.charValue());
                    cTmp = null;
                }
                do
                {
                    char c = (char)comverse.getInputStream().read();
                    if(c == ';')
                    {
                        c = (char)comverse.getInputStream().read();
                        if(c != '|')
                            cTmp = new Character(c);
                        break;
                    }
                    sb.append(c);
                } while(true);
                String trama = (new StringBuilder()).append(toChar("yy-MM-dd HH:mm:ss")).append(" ").append(sb.toString().trim()).toString();
                System.out.print((new StringBuilder()).append(serverName).append(">> ").append(trama).toString());
                pwCliente.println(trama);
                pwCliente.flush();
                int res = cliente.getInputStream().read();
                int cont = 0;
                for(; res != 5; res = cliente.getInputStream().read())
                {
                    System.out.println((new StringBuilder()).append("\nIntento[").append(++cont).append("]").toString());
                    Thread.sleep(2000L);
                    if(cont >= 5)
                        println(pwf, (new StringBuilder()).append("Error: Al recibir respuesta del ").append(serverName).toString());
                }

                System.out.println(res != 5 ? "[FAIL]" : "[OK]");
            } while(true);
        }
        catch(IOException e)
        {
            println(pwf, (new StringBuilder()).append("Error: Al envia la trama[").append(e.getMessage()).append("]").toString());
        }
        System.exit(1);

    }

    public static String toChar(Date d, String pattern){
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        return df.format(d);
        //"dd MMM yyyy HH:mm"
    }

    public static String toChar(String pattern){
        return toChar(new Date(), pattern);
        //"dd MMM yyyy HH:mm"
    }

    public static void println(PrintWriter pw, String txt) {
        println(pw, txt, true);
    }

    public static void print(PrintWriter pw, String txt) {
        print(pw, txt, true);
    }

    public static void debug(PrintWriter pw, String txt){
        pw.print(txt);
        pw.flush();
    }

    public static void println(PrintWriter pw, String txt, boolean out) {
        SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm");

        pw.println(df.format(new Date()) + " >> " + txt);
        pw.flush();
        if(out)
            System.out.println(txt);
    }


    public static void print(PrintWriter pw, String txt, boolean out) {
        SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm");

        pw.print(df.format(new Date()) + " >> " + txt);
        pw.flush();
        if(out)
            System.out.print(txt);
    }
    
}

